package com.sunshine.wrongquestionset.activity.question

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.Html
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.add_question.AddQuestionActivity
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.callback.OnClickListener
import com.sunshine.wrongquestionset.callback.QuestionOptionsListener
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.sunshine.wrongquestionset.room.entity.QuestionInfoEntity
import com.sunshine.wrongquestionset.room.entity.QuestionTypeEntity
import com.sunshine.wrongquestionset.utils.AnalyzerUtils
import com.sunshine.wrongquestionset.view.QuestionContentBottomSheetDialog
import kotlinx.android.synthetic.main.activity_question.*
import java.text.DecimalFormat

class QuestionActivity : BaseActivity() {

    private lateinit var viewModel: QuestionViewModel
    //百分数保留2位
    private val decimalFormat = DecimalFormat("0.##%")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_question)
        setTitle(getString(R.string.label_question))

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(QuestionViewModel::class.java)

        val type = intent?.getIntExtra("type", TYPE_ALL)?:0
        val subjectId = intent?.getIntExtra("subjectId", -1)?:-1
        val setId = intent?.getIntExtra("setId", -1)?:-1

        val observer = Observer<List<QuestionEntity>?> {
            recyclerView.setLayoutManager(LinearLayoutManager(this))
            val adapter = QuestionAdapter(
                it,
                object : OnClickListener {
                    @SuppressLint("SetTextI18n")
                    override fun onClick(position: Int) {
                        val questionEntity = it!![position]

                        val questionInfoLiveData = viewModel.getQuestionInfoByQuestionId(questionEntity.id)
                        var questionInfoObserver: Observer<List<QuestionInfoEntity>?>? = null
                        questionInfoObserver = Observer {questionInfoList ->

                            val wrongQuestionBeanByQuestionIdLiveData = viewModel.getWrongQuestionBeanByQuestionId(questionEntity.id)
                            wrongQuestionBeanByQuestionIdLiveData.observe(this@QuestionActivity, Observer {wrongQuestionBeanList ->
                                val questionFamiliarityBean = AnalyzerUtils.analyzerQuestionFamiliarity(questionInfoList, 10)

                                val questionTypeLiveData = viewModel.getQuestionType(questionEntity.typeId)
                                var questionTypeObserver: Observer<String?>? = null
                                questionTypeObserver = Observer {type->
                                    QuestionContentBottomSheetDialog.show(
                                        this@QuestionActivity,
                                        questionEntity.titlePath,
                                        questionEntity.answerPath,
                                        "题目类型：$type 熟悉程度：${decimalFormat.format(questionEntity.familiarity)}",
                                        questionFamiliarityBean,
                                        wrongQuestionBeanList,
                                        object : QuestionOptionsListener {
                                            override fun onDelete() {
                                                //删除题目
                                                val builder = MaterialAlertDialogBuilder(this@QuestionActivity)
                                                builder.apply {
                                                    setTitle(context.getString(R.string.warning_title))
                                                    setMessage(Html.fromHtml(context.getString(R.string.delete_question_warning)))
                                                    setPositiveButton("我再想想") {_, _ ->}
                                                    setNegativeButton("删除") {_, _ ->
                                                        viewModel.deleteQuestion(questionEntity)
                                                        Snackbar.make(question_root, getString(R.string.delete_success), Snackbar.LENGTH_SHORT).show()
                                                    }
                                                }
                                                builder.create().show()
                                            }

                                            override fun onEdit() {
                                                AddQuestionActivity.editQuestionEntity = questionEntity
                                                val intent = Intent(this@QuestionActivity, AddQuestionActivity::class.java)
                                                intent.putExtra("type", AddQuestionActivity.TYPE_EDIT)
                                                startActivity(intent)
                                            }

                                        }
                                    )
                                    //用后移除观察者，否则数据变化会多次调用
                                    questionTypeLiveData.removeObserver(questionTypeObserver!!)
                                }
                                questionTypeLiveData.observe(this@QuestionActivity, questionTypeObserver)

                                wrongQuestionBeanByQuestionIdLiveData.removeObservers(this@QuestionActivity)
                            })
                            //用后移除观察者，否则数据变化会多次调用
                            questionInfoLiveData.removeObserver(questionInfoObserver!!)
                        }

                        //练习记录熟悉程度变化折线图
                        questionInfoLiveData.observe(this@QuestionActivity, questionInfoObserver)
                    }

                    override fun onLongClick(position: Int) {

                    }
                }
            )

            recyclerView.setAdapter(adapter)
        }

        when (type) {
            TYPE_QUESTION_SET -> {
                viewModel.getQuestionBySet(setId).observe(this, observer)
            }
            TYPE_SUBJECT -> {
                viewModel.getQuestionBySubject(subjectId).observe(this, observer)
            }
            TYPE_ALL -> {
                viewModel.getAllQuestion(getLoginUserId()).observe(this, observer)
            }
        }

        fab_add_question.setOnClickListener {
            val intent = Intent(this, AddQuestionActivity::class.java)
            if (subjectId != -1) intent.putExtra("subjectId", subjectId)
            if (setId != -1) intent.putExtra("setId", setId)
            startActivity(intent)
        }
    }

    companion object {
        const val TYPE_ALL = 0
        const val TYPE_QUESTION_SET = 1
        const val TYPE_SUBJECT = 2
    }
}